﻿using JetBrains.ReSharper.Daemon.CSharp.Stages;
using JetBrains.ReSharper.Daemon.Stages;
using JetBrains.ReSharper.Daemon.Stages.Dispatcher;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.Util;
using MugenMvvmToolkit.ReSharper.Highlighting;
using MugenMvvmToolkit.ReSharper.Infrastructure;

namespace MugenMvvmToolkit.ReSharper.ViewModels.Analyzers
{
    [ElementProblemAnalyzer(new[] { typeof(IAttributesOwnerDeclaration) },
        HighlightingTypes = new[] { typeof(UnusedTaskHandlerAttributeHighlighting) })]
    public class SuppressTaskHandlerAttributeAnalyzer : ElementProblemAnalyzerBase<IAttributesOwnerDeclaration>
    {
        #region Overrides of ElementProblemAnalyzerBase<IAttribute>

        protected override void Run(IAttributesOwnerDeclaration element, ElementProblemAnalyzerData data,
            IHighlightingConsumer consumer)
        {
            element.Attributes.ForEach(attribute => Proccess(attribute, element, consumer));
        }

        #endregion

        #region Methods

        private void Proccess(IAttribute attribute, IAttributesOwnerDeclaration owner, IHighlightingConsumer consumer)
        {
            var @class = attribute.GetReferenceDeclaredElement<IClass>();
            if (@class == null || !(@class.IsOfType(TypeProvider.SuppressTaskBusyHandlerAttribute)))
                return;
            var parametersOwner = owner.DeclaredElement as IParametersOwner;
            if (parametersOwner == null || !parametersOwner.ReturnType.IsOfType(TypeProvider.Task))
                consumer.AddHighlighting(new UnusedTaskHandlerAttributeHighlighting(attribute,
                    UiResources.SuppressTaskBusyHandlerInvalidMethodSignature));
        }

        #endregion
    }
}